package br.com.recipe.web;

import java.io.IOException;
import java.rmi.ServerException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Transaction;

/**
 * Servlet Filter implementation class HibernateRequestFilter
 */
public class HibernateRequestFilter implements Filter {
	private static Log log = LogFactory.getLog(HibernateRequestFilter.class);
	//private SessionFactory sessionFactory;
	
    public HibernateRequestFilter() {}
    
    public void init(FilterConfig fConfig) throws ServletException { }
    
	public void destroy() {}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		boolean commit = false;
		Transaction tx = null;
		
		try {
			chain.doFilter(request, response);	
			commit = true;
		} catch (ServerException se) {
			log.warn(se);
		} catch (IOException ie) {
			log.warn(ie);
		} catch (RuntimeException re) {
			log.warn(re);
		} finally {			
		/**	try {
				tx = HibernateSessionFactory.getTransaction();
			} catch (RecipeException e) {
				//log.warn(e);
			} **/
			if ((tx != null) && tx.isActive() && commit) {
				tx.commit();
			} else {
				tx.rollback();
			}
		}
		
	}

}
